package xyz.vmcserver.wdibbs.model.service;

import org.apache.commons.codec.binary.Hex;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.logging.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import xyz.vmcserver.wdibbs.model.vo.Article;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Logger;

public class ToolsService {
    /***
     * 利用Apache的工具类实现SHA-256加密
     *
     * @param str 需要加密的报文
     * @return encdeStr 加密后的报文
     */
    public String getSHA256Str(String str) {
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        System.out.println("加密后："+encdeStr);
        return encdeStr;
    }
    public String getRandomStr(Integer strNum){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random1=new Random();
        //指定字符串长度，拼接字符并toString
        StringBuffer sb=new StringBuffer();
        for (int i = 0; i < strNum; i++) {
            //获取指定长度的字符串中任意一个字符的索引值
            int number=random1.nextInt(str.length());
            //根据索引值获取对应的字符
            char charAt = str.charAt(number);
            sb.append(charAt);
        }
        String str1 = String.valueOf(sb);
        return str1;
    }


    public String pageGeneration(HttpServletRequest request, Article article, String uniqueCode, String content) throws IOException {
            String filePath = "";
            filePath = request.getSession().getServletContext().getRealPath("/WEB-INF/pages/module/")+"article_template.html";  //这个页面为模板页面,支持多种格式
            String templateContent="";
            FileInputStream fileinputstream = new FileInputStream(filePath);//读取模块文件
            int lenght = fileinputstream.available();
            byte bytes[] = new byte[lenght];
            fileinputstream.read(bytes);
            fileinputstream.close();
            templateContent = new String(bytes,"UTF-8");
            templateContent=templateContent.replaceAll("<!--title_start--><!--title_stop-->",
                    article.getTitle());
            templateContent=templateContent.replaceAll("<!--content_start--><!--content_stop-->",
                    "<!--content_start-->"+content+"<!--content_stop-->");
            templateContent=templateContent.replaceAll("<!--author_start--><!--author_stop-->",
                    "<!--author_start-->"+article.getCreatorUsername()+"<!--author_stop-->");
            templateContent=templateContent.replaceAll("<!--create_time_start--><!--create_time_stop-->",
                    "<!--create_time_start-->"+article.getCreateTime()+"<!--create_time_stop-->");
            templateContent=templateContent.replaceAll("<!--redactor_start--><!--redactor_stop-->",
                    "<!--redactor_start-->"+article.getRedactorUsername()+"<!--redactor_stop-->");
            templateContent=templateContent.replaceAll("<!--redact_time_start--><!--redact_time_stop-->",
                    "<!--redact_time_start-->"+article.getRedactTime()+"<!--redact_time_stop-->");
            String filename =uniqueCode+".html";
            filename = request.getSession().getServletContext().getRealPath("/article/")+filename;//生成的html文件保存路径
            FileWriter out = new FileWriter(filename);    //基于“字符”的输出操作
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    new FileOutputStream(filename),"UTF-8"
            );
            outputStreamWriter.write(templateContent);
            outputStreamWriter.flush();
            outputStreamWriter.close();
            return "9999";
    }
    public Integer Base64ToFile(String base64, String filePath) throws IOException {
        // base64编码字符必须不能包含base64的前缀，否则会报错
        // filePath需要为具体到文件的名称和格式，如111.txt
        // 文件路径需要双斜杠转义，如:  D:\\files\\111.txt
        if (base64 == null && filePath == null) {
            return 0;
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        filePath+=timestamp.getTime();
        // 判断是否base64是否包含data:image/png;base64等前缀，如果有则去除
        if (base64.contains("data:image/png;base64")) {
            base64 = base64.substring(22);
            System.out.println("包含png"+base64);
            filePath+=".png";
        }
        if (base64.contains("data:image/jpeg;base64")) {
            base64 = base64.substring(23);
            System.out.println("包含jpeg"+base64);
            filePath+=".jpeg";
        }
        if (base64.contains("data:application/pdf;base64")) {
            base64 = base64.substring(28);
            System.out.println("包含pdf"+base64);
            filePath+=".pdf";
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64);
        for (int i = 0; i<bytes.length; ++i) {
            // 调整异常数据
            if (bytes[i] < 0) {
                bytes[i] +=256;
            }
        }
        OutputStream outputStream = null;
        InputStream inputStream = new ByteArrayInputStream(bytes);
        // 此处判断文件夹是否存在，不存在则创建除文件外的父级文件夹
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("上级目录"+file.getParentFile());
            file.getParentFile().mkdirs();
        }
        try {
            // 生成指定格式文件
            System.out.println(filePath);
            outputStream = new FileOutputStream(filePath);
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.flush();
            outputStream.close();
        }
        return 1;
    }



}
